//
//  WBOAuthViewController.swift
//  个人微博
//
//  Created by 任聪聪 on 2017/11/30.
//  Copyright © 2017年 任孜聪. All rights reserved.
//

import UIKit
import SVProgressHUD
//定义微博授权登录界面
class WBOAuthViewController: UIViewController {
    //设置webView为跳转界面窗体
    fileprivate lazy var webView = UIWebView()
    override func loadView() {
        //设置webView为当前视图
        view = webView
        view.backgroundColor = UIColor.white
        //设置当前视图不能滚动
        webView.scrollView.isScrollEnabled = false
        navigationItem.title = "新浪微博登录"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", any: self, action: #selector(back), isBack: true)
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", any: self, action: #selector(autoFill))
        //设置webView代理获取跳转到授权页面授权码
        webView.delegate = self
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        //1.加载授权页面
        //1>拼接授权地址
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WebAppKey)&redirect_uri=\(WebRedirctUri)"
        //2>生成URL类型地址
        guard let url = URL(string: urlString) else {
            return
        }
        //3>生成URLRequset请求
        let request = URLRequest(url: url)
        //4>向服务器发起请求
        webView.loadRequest(request)
        
    }
    //监听事件
    func back()  {
        //取消的时候菊花显示应该消失
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    //自动填充账号密码,开发者可以任意修改本地浏览器的账号密码保存在本地缓存文件中
    //点击登录时将会把缓存文件提交到服务器中
    func autoFill() {
        //1.js代码准备
        let js = "document.getElementById('userId').value='2212650959@qq.com';"+"document.getElementById('passwd').value='rzc2268603';"
        //2.WebView加载js代码
         webView.stringByEvaluatingJavaScript(from: js)
    }
}
extension WBOAuthViewController:UIWebViewDelegate{
    //设置代理获取跳转页面的授权码
    //加载将要跳转的页面
    
    /// <#Description#>
    ///
    /// - Parameters:
    ///   - webView: <#webView description#>
    ///   - request: 加载请求
    ///   - navigationType: 导航栏类型
    /// - Returns: <#return value description#>
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //1.获取跳转页面授权码思路如果有http://baidu.com/ 就不加载如果没有才加载
        //request.url?.absoluteString.hasPrefix("//baidu.com/")可选项判断返回boolean值 true／false／nil
        if request.url?.absoluteString.hasPrefix("http://baidu.com/") == false{
            return true
        }
        //2.从回调地址的查询字符串中提取含有‘code=’的字符串
        //request.url?.query 表示查询字符串 “？”之后的所有字符
        if request.url?.query?.hasPrefix("code=") == false{
            back()
            return false
        }
        //3.如果有授权成功，没有授权失败
//        print("加载跳转页面\(request.url?.absoluteString)")
//        print("加载跳转页面\(request.url?.query)")
        //4.授权成功之后获取授权码，代码到此查询字符中一定含有code=
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        print("授权码 -\(code)")
        //5.根据授权码获取（换取）acessToken
        WBNetWorkManager.shared.getacessToken(code: code) { (isSucess) in
            if !isSucess{
                SVProgressHUD.showInfo(withStatus: "网络请求失败")
            }else{
                SVProgressHUD.showInfo(withStatus: "登录成功")
                //1.发送通知，通知并不需要有监听者，只负责将消息发布出去。
                NotificationCenter.default.post(
                    name: NSNotification.Name(rawValue: WBUserLoginSucessNotification),
                    object: nil)
                //2.关闭当前视图
                self.back()
            }
        }
        return false
    }
    func webViewDidStartLoad(_ webView: UIWebView) {
        //开始加载的时候显示菊花等待
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
        //加载结束的时候菊花消失
        SVProgressHUD.dismiss()
    }
}
